package com.wechat.utils;

import java.util.ResourceBundle;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.wechat.model.wechat.AccessToken;
import com.wechat.model.wechat.JsapiTicket;

/**
 * 定时获取微信access_token的线程
 * @author liuyq
 * @date 2013-05-02
 */
public class TokenThread implements Runnable {
	private static Logger log = LoggerFactory.getLogger(TokenThread.class);
	public static String appid = null;
	public static String appsecret = null;
	public static AccessToken accessToken = null;
	public static JsapiTicket jsapiTicket = null;
	static {
		ResourceBundle bundle = ResourceBundle.getBundle("config.environments.wechatapp");
		appid = bundle.getString("appid");
		appsecret = bundle.getString("appsecret");
	}

	public void run() {
		while (true) {
			try {
				accessToken = WechatMessageUtils.getAccessToken(WechatMessageUtils.APPID, WechatMessageUtils.APPSECRET);
				// String url =
				// "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token="
				// +accessToken.getToken() ;
				if (null != accessToken) {
					log.info("获取access_token成功，有效时长{}秒 token:{}", accessToken.getExpiresIn(), accessToken.getToken());
					System.out.println("获取access_token成功!-----------------------------------------------------");

					// ********************* 获取 jsapi ticket
					jsapiTicket = WechatMessageUtils.getJsapiTicket(accessToken.getToken());
					if (jsapiTicket != null) {
						log.info("获取jsapi_ticket成功，有效时长{}秒 jsapi_ticket成功:{}", jsapiTicket.getExpiresIn(), jsapiTicket.getJsapticket());
						System.out.println("获取jsapi_ticket成功!-----------------------------------------------------");
					} else {
						log.info("获取jsapi_ticket获取失败");
						System.out.println("获取jsapi_ticket失败!-----------------------------------------------------");
					}
					// 休眠7000秒
					Thread.sleep(7000 * 1000);
				} else {
					// 如果access_token为null，60秒后再获取
					Thread.sleep(60 * 1000);
				}
			} catch (InterruptedException e) {
				try {
					Thread.sleep(60 * 1000);
				} catch (InterruptedException e1) {
					log.error("{}", e1);
				}
				log.error("{}", e);
			}
		}
	}
}